import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as API from "../api/http";

//存放数据
let initialState = {
    typelist: [],//分类数据
    shoplist: [],//商品列表数据
    carlist: [],//购物车数据
    tang: false,
    xiguan: '1',
}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步修改

        //获取分类数据
        t_gettypelist(state, action) {
            state.typelist = action.payload
        },
        //获取商品列表数据
        t_getshoplist(state, action) {
            state.shoplist = action.payload
        },
        //获取购物车数据
        t_getcarlist(state, action) {
            state.carlist = action.payload
        },
        //添加购物车数据
        t_addcarlist(state, action) {
            state.carlist.push(action.payload)
        },
        //编辑商品列表数据
        t_updateshoplist(state, action) {
            let i = state.shoplist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.shoplist[i] = action.payload
        },
       
    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

//异步操作
//获取分类列表数据
export let async_gettypelist = createAsyncThunk('async_gettypelist',
    async (_, store) => {
        //调取接口
        let res = await API.http_gettypelist()
        //同步修改异步
        store.dispatch(actionfn.t_gettypelist(res))

    })

//获取商品列表数据
export let async_getshoplist = createAsyncThunk('async_getshoplist',
    async (_, store) => {
        //调取接口
        let res = await API.http_getshoplist()
        //同步修改异步
        store.dispatch(actionfn.t_getshoplist(res))

    })

//获取购物车列表数据
export let async_getcarlist = createAsyncThunk('async_getcarlist',
    async (_, store) => {
        //调取接口
        let res = await API.http_getcarlist()
        //同步修改异步
        store.dispatch(actionfn.t_getcarlist(res))

    })
//添加购物车列表数据
export let async_addcarlist = createAsyncThunk('async_addcarlist',
    async (obj, store) => {
        //获取接口
        let res = await API.http_addcarlist(obj)
        //同步修改异步
        store.dispatch(actionfn.t_addcarlist(res))
    })
//编辑商品列表数据
export let async_updateshoplist = createAsyncThunk('async_updateshoplist',
    async (obj, store) => {
        //调取接口
        let res = await API.http_updateshoplist(obj)
        //同步修改异步
        store.dispatch(actionfn.t_updateshoplist(res))
    })